import os
import yaml
import logging
from flask import jsonify
from .ai_analyzer import AIAnalyzer

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class FlowService:
    def __init__(self):
        self.base_path = os.path.join(os.path.dirname(__file__), 'DSL')
        self.index_file = os.path.join(self.base_path, 'index', 'flow_index.yaml')
        self.flows_dir = os.path.join(self.base_path, 'flows')
        self.prompt_template_file = os.path.join(self.base_path, 'prompt.txt') # Add this line
        self.ai_analyzer = AIAnalyzer()
        logger.info(f"FlowService initialized with index file: {self.index_file}")
        logger.info(f"Flows directory: {self.flows_dir}")
        
        # 验证文件和目录是否存在
        if not os.path.exists(self.index_file):
            logger.error(f"Flow index file not found: {self.index_file}")
        if not os.path.exists(self.flows_dir):
            logger.error(f"Flows directory not found: {self.flows_dir}")

    def get_flows(self):
        """获取所有flow的列表"""
        try:
            logger.info(f"Reading flow index from: {self.index_file}")
            if not os.path.exists(self.index_file):
                logger.error(f"Flow index file not found: {self.index_file}")
                return []

            with open(self.index_file, 'r', encoding='utf-8') as f:
                data = yaml.safe_load(f)
                logger.info(f"Raw YAML data: {data}")
                flows = data.get('flows', [])
                logger.info(f"Found {len(flows)} flows in index")
                for flow in flows:
                    logger.info(f"Flow: {flow}")
                return flows
        except Exception as e:
            logger.error(f"Error reading flow index: {e}")
            return []

    def get_flow_content(self, flow_id):
        """获取指定flow的内容"""
        flows = self.get_flows()
        flow = next((f for f in flows if f['id'] == flow_id), None)
        if not flow:
            logger.error(f"Flow not found: {flow_id}")
            return None

        try:
            flow_file = os.path.join(self.flows_dir, flow['file'])
            logger.info(f"Reading flow content from: {flow_file}")
            if not os.path.exists(flow_file):
                logger.error(f"Flow file not found: {flow_file}")
                return None

            with open(flow_file, 'r', encoding='utf-8') as f:
                content = f.read()
                return {'content': content}
        except Exception as e:
            logger.error(f"Error reading flow content: {e}")
            return None

    def delete_flow(self, flow_id):
        """删除指定的flow"""
        try:
            # 读取现有的flow_index.yaml
            with open(self.index_file, 'r', encoding='utf-8') as f:
                data = yaml.safe_load(f)
                if not data or 'flows' not in data:
                    logger.error("Invalid flow index file format")
                    return False

            # 查找要删除的flow
            flow = next((f for f in data['flows'] if f['id'] == flow_id), None)
            if not flow:
                logger.error(f"Flow not found: {flow_id}")
                return False

            # 删除flow文件
            flow_file = os.path.join(self.flows_dir, flow['file'])
            if os.path.exists(flow_file):
                os.remove(flow_file)
                logger.info(f"Deleted flow file: {flow_file}")

            # 从index中移除flow
            data['flows'] = [f for f in data['flows'] if f['id'] != flow_id]

            # 更新flow_index.yaml
            with open(self.index_file, 'w', encoding='utf-8') as f:
                yaml.safe_dump(data, f, allow_unicode=True, sort_keys=False)

            logger.info(f"Flow deleted successfully: {flow_id}")
            return True

        except Exception as e:
            logger.error(f"Error deleting flow: {e}")
            return False

    def create_flow(self, flow_data):
        """创建新的flow"""
        try:
            # 验证flow ID是否已存在
            flows = self.get_flows()
            if any(f['id'] == flow_data['id'] for f in flows):
                logger.error(f"Flow ID already exists: {flow_data['id']}")
                return False

            # 读取现有的flow_index.yaml
            with open(self.index_file, 'r', encoding='utf-8') as f:
                data = yaml.safe_load(f) or {'flows': []}

            # 添加新的flow
            data['flows'].append({
                'id': flow_data['id'],
                'file': flow_data['file'],
                'description': flow_data['description']
            })

            # 创建新的flow文件
            flow_file = os.path.join(self.flows_dir, flow_data['file'])
            with open(flow_file, 'w', encoding='utf-8') as f:
                f.write(f"id: {flow_data['id']}\ndescription: {flow_data['description']}\n")

            # 更新flow_index.yaml
            with open(self.index_file, 'w', encoding='utf-8') as f:
                yaml.safe_dump(data, f, allow_unicode=True, sort_keys=False)

            logger.info(f"Flow created successfully: {flow_data['id']}")
            return True

        except Exception as e:
            logger.error(f"Error creating flow: {e}")
            return False

    def update_flow_content(self, flow_id, content):
        """更新指定flow的内容"""
        flows = self.get_flows()
        flow = next((f for f in flows if f['id'] == flow_id), None)
        if not flow:
            logger.error(f"Flow not found: {flow_id}")
            return False

        try:
            # 验证YAML格式
            try:
                yaml.safe_load(content)
            except yaml.YAMLError as e:
                logger.error(f"Invalid YAML content: {e}")
                raise ValueError(f"Invalid YAML format: {e}")

            # 写入文件
            flow_file = os.path.join(self.flows_dir, flow['file'])
            logger.info(f"Writing flow content to: {flow_file}")
            
            # 创建备份
            if os.path.exists(flow_file):
                backup_file = f"{flow_file}.bak"
                os.rename(flow_file, backup_file)
                logger.info(f"Created backup: {backup_file}")

            try:
                with open(flow_file, 'w', encoding='utf-8') as f:
                    f.write(content)
                logger.info(f"Successfully updated flow content: {flow_id}")
                
                # 删除备份
                if os.path.exists(backup_file):
                    os.remove(backup_file)
                    logger.info(f"Removed backup file: {backup_file}")
                
                return True
            except Exception as write_error:
                # 如果写入失败，恢复备份
                if os.path.exists(backup_file):
                    os.rename(backup_file, flow_file)
                    logger.info(f"Restored from backup: {backup_file}")
                raise write_error

        except Exception as e:
            logger.error(f"Error updating flow content: {e}")
            return False

    def smart_generate_flow(self, prompt: str):
        """智能生成Flow"""
        try:
            logger.info(f"Starting smart flow generation with prompt: {prompt}")
            
            # 读取prompt.txt内容作为AI的指令
            ai_instruction = ""
            if os.path.exists(self.prompt_template_file):
                with open(self.prompt_template_file, 'r', encoding='utf-8') as f:
                    ai_instruction = f.read()
            else:
                logger.warning(f"Prompt template file not found: {self.prompt_template_file}")

            full_prompt = f"{ai_instruction}\n\n用户需求: {prompt}"

            # 使用AIAnalyzer生成Flow内容
            # generated_content = self.ai_analyzer.analyze_and_refine_flow("", full_prompt) # First param can be empty for new generation
            messages = [{'role': 'user', 'content': full_prompt}]
            generated_content = self.ai_analyzer._call_ai_api_with_messages(messages, stream=False)

            # 从生成内容中解析ID、文件名和描述
            # 假设生成的YAML内容中包含id, file, description字段
            generated_yaml = yaml.safe_load(generated_content)
            flow_id = generated_yaml.get('id', f'generated_flow_{len(self.get_flows()) + 1}')
            flow_file_name = generated_yaml.get('file', f'{flow_id}.yaml')
            flow_description = generated_yaml.get('description', '智能生成的Flow')

            new_flow_data = {
                'id': flow_id,
                'file': flow_file_name,
                'description': flow_description
            }
            
            # 检查生成的flow ID是否已存在，如果存在则生成新的
            counter = 1
            original_flow_id = flow_id
            while any(f['id'] == flow_id for f in self.get_flows()):
                flow_id = f'{original_flow_id}_{counter}'
                flow_file_name = f'{flow_id}.yaml'
                new_flow_data['id'] = flow_id
                new_flow_data['file'] = flow_file_name
                counter += 1

            # 创建Flow并保存内容
            success = self.create_flow_with_content(new_flow_data, generated_content)

            if success:
                logger.info(f"Smart generated flow successfully: {flow_id}")
                return {**new_flow_data, 'content': generated_content} # Return the content as well
            else:
                raise Exception("Failed to create flow after smart generation")

        except Exception as e:
            logger.error(f"Error smart generating flow: {e}")
            raise

    def create_flow_with_content(self, flow_data, content):
        """创建新的flow并写入指定内容"""
        try:
            # 读取现有的flow_index.yaml
            with open(self.index_file, 'r', encoding='utf-8') as f:
                data = yaml.safe_load(f) or {'flows': []}

            # 添加新的flow到index
            data['flows'].append({
                'id': flow_data['id'],
                'file': flow_data['file'],
                'description': flow_data['description']
            })

            # 创建新的flow文件并写入内容
            flow_file = os.path.join(self.flows_dir, flow_data['file'])
            with open(flow_file, 'w', encoding='utf-8') as f:
                f.write(content)

            # 更新flow_index.yaml
            with open(self.index_file, 'w', encoding='utf-8') as f:
                yaml.safe_dump(data, f, allow_unicode=True, sort_keys=False)

            logger.info(f"Flow with content created successfully: {flow_data['id']}")
            return True

        except Exception as e:
            logger.error(f"Error creating flow with content: {e}")
            return False